export const decodeScene = (scene) => {
	let decodeScene = ''
	if (uni.getSystemInfoSync().platform == "ios") {
		decodeScene = decodeURIComponent(decodeURIComponent(scene));
	} else {
		decodeScene = decodeURIComponent(scene);
	}
	return decodeScene.split('&');
}

// 上传文件
import {
	apiBaseUrl,
} from '@/common/setting/constVarsHelper.js';
import store from '@/store';
export const uploadFilePromise = (url, type, isLoading = true) => {
	if (isLoading) {
		uni.showLoading({
			mask: true,
			title: '加载中... '
		});
	}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: `${apiBaseUrl}/v5-wf-api/v1/instancehandle/uploadfile/${type}`,
			filePath: url,
			header: {
				Authorization: 'Bearer ' + store.state.accessToken,
			},
			name: 'files',
			success: (uploadFileRes) => {
				setTimeout(() => {
					resolve(JSON.parse(uploadFileRes.data).data[0])
				}, 1000)
			},
			fail() {
				resolve(false)
			},
			complete() {
				if (isLoading) {
					uni.hideLoading();
				}
			}
		});
	})
}

// 识别图片文本
export const uploadOcrPromise = (url, type, isLoading = true) => {
	console.log(url, 'uploadOcrPromise')
	if (isLoading) {
		uni.showLoading({
			mask: true,
			title: '加载中... '
		});
	}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: `https://test.fengze.cloud/wf-ocr-api/ApiOcr/getocrdata/${type}`,
			filePath: url,
			header: {
				Authorization: 'Bearer ' + store.state.accessToken,
			},
			name: 'file',
			success: (uploadFileRes) => {
				console.log(uploadFileRes, 'uploadFileRes')
				setTimeout(() => {
					resolve(uploadFileRes.data.replace(/(\n|\r|\r\n|↵)/g, '<br />'))
				}, 1000)
			},
			fail() {
				resolve(false)
			},
			complete() {
				if (isLoading) {
					uni.hideLoading();
				}
			}
		});
	})
}

// 克隆函数
export const deepClone = (obj, newObj) => {
	if (obj instanceof Array) { // 判断是否是数组
		newObj = [];
		return deepCloneArray(obj, newObj);
	} else if (obj instanceof Object && typeof obj === 'object') { // 判断是否是对象
		newObj = {};
		return deepCloneObject(obj, newObj);
	} else {
		return newObj = obj;
	}
}
// 克隆对象
function deepCloneObject(obj, newObj) {
	for (var temp in obj) {
		if (obj.hasOwnProperty(temp)) { // 过滤原型属性
			if (obj[temp] instanceof Object || obj[temp] instanceof Array) { // 如果还是对象或者数组继续递归深层克隆
				var tempNewObj = {};
				newObj[temp] = deepClone(obj[temp],
					tempNewObj);
			} else { // 不是直接赋值
				newObj[temp] = obj[temp];
			}
		}
	}
	return newObj;
}
// 克隆数组
function deepCloneArray(arr, newArr) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i] instanceof Object || arr[i] instanceof Array) { // 如果还是对象或者数组继续递归深层克隆
			var tempNewObj;
			newArr[i] = deepClone(arr[i], tempNewObj);
		} else { // 不是直接赋值
			newArr[i] = arr[i];
		}
	}
	return newArr;
}

// date 代表指定的日期，格式：2018-09-27
// day 传-1表始前一天，传1表始后一天
// JS获取指定日期的前一天，后一天
export const getNextDate = (date, day) => {
	let dd = new Date(date);
	dd.setDate(dd.getDate() + day);
	let y = dd.getFullYear();
	let m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
	let d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
	return y + "-" + m + "-" + d;
}


// 文件大小显示单位
export const transformSize = (size) => {
	if (size < 1024) {
		// B
		return size + 'B'
	} else if (size / 1024 / 1024 >= 1) {
		// MB
		return (size / 1024 / 1024).toFixed(2) + 'MB'
	} else {
		// KB
		return (size / 1024).toFixed(2) + 'KB'
	}
}

/**
 * 生成一个随机字符串
 * @param {Object} length
 */
export const randomString = (size = 12) => {
	let urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
	let id = ''
	let i = size
	while (i--) {
		id += urlAlphabet[(Math.random() * 64) | 0]
	}
	return id
}

/**
 * 退回匹配到的路由
 * @param {路由} route 
 */
export const navigatorBackRoute = (route) => {
	const routeList = getCurrentPages();
	let index = 1;
	routeList.forEach((item, i) => {
		if (item.route === route) {
			index = i;
		}
	})
	uni.$emit('refresh');
	uni.navigateBack({
		delta: routeList.length - index - 1
	});
}

// 上传用户头像
export const uploadUserFilePromise = (url, type, isLoading = true) => {
	if (isLoading) {
		uni.showLoading({
			mask: true,
			title: '加载中... '
		});
	}
	return new Promise((resolve, reject) => {
		console.log(url, 'uploadUserFilePromise')
		uni.uploadFile({
			url: `${apiBaseUrl}/cloud/api/apidownload/api/upload/upload`,
			filePath: url,
			header: {
				Authorization: 'Bearer ' + store.state.accessToken,
			},
			name: 'file',
			success: (uploadFileRes) => {
				console.log(uploadFileRes, 'uploadFileRes')
				setTimeout(() => {
					resolve(JSON.parse(uploadFileRes.data))
				}, 1000)
			},
			fail() {
				resolve(false)
			},
			complete() {
				if (isLoading) {
					uni.hideLoading();
				}
			}
		});
	})
}

// 上传用户头像
export const uploadWWCompanyFilePromise = (url, type, isLoading = true) => {
	if (isLoading) {
		uni.showLoading({
			mask: true,
			title: '加载中... '
		});
	}
	return new Promise((resolve, reject) => {
		console.log(url, 'uploadUserFilePromise')
		uni.uploadFile({
			url: `${apiBaseUrl}/cloud/api/apidownload/api/upload/uploadWWCompany			`,
			filePath: url,
			header: {
				Authorization: 'Bearer ' + store.state.accessToken,
			},
			name: 'file',
			success: (uploadFileRes) => {
				console.log(uploadFileRes, 'uploadFileRes')
				setTimeout(() => {
					resolve(JSON.parse(uploadFileRes.data))
				}, 1000)
			},
			fail() {
				resolve(false)
			},
			complete() {
				if (isLoading) {
					uni.hideLoading();
				}
			}
		});
	})
}


/**
 * 图片预览功能
 * @param {图片数组} urls 
 * @param {可以是图片的链接，或者图片的下标} current 
 */
export const perviewImages = (urls, current = 0) => {
	// 预览图片
	// #ifndef APP-PLUS
	uni.previewImage({
		current,
		urls,
	});
	// #endif
	// #ifdef APP-PLUS
	plus.nativeUI.previewImage(urls, {
		"background": "#ffffff"
	});
	// #endif
}

// 获取状态条的高度
export const initStatusBarHeight = (urls) => {
	let statusHeight = 20;
	let totalHeight = 20;
	const systemInfo = uni.getSystemInfoSync()
	statusHeight = systemInfo.statusBarHeight ? systemInfo.statusBarHeight * 2 : 20;
	totalHeight = 'var(--status-bar-height)'
	// #ifdef MP-WEIXIN
	const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
	statusHeight = menuButtonInfo.top * 2;
	totalHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + systemInfo.statusBarHeight +
		menuButtonInfo.height
	// #endif
	return statusHeight;
}

// 颜色渐变
export const approximateColor1ToColor2ByPercent = (color1, color2 = "#ffffff", percent) => {
    let red1 = parseInt(color1[1] + color1[2], 16);
    let green1 = parseInt(color1[3] + color1[4], 16);
    let blue1 = parseInt(color1[5] + color1[6], 16);

    let red2 = parseInt(color2[1] + color2[2], 16);
    let green2 = parseInt(color2[3] + color2[4], 16);
    let blue2 = parseInt(color2[5] + color2[6], 16);

    let red = Math.round(mix(red1, red2, percent));
    let green = Math.round(mix(green1, green2, percent));
    let blue = Math.round(mix(blue1, blue2, percent));

    return generateHex(red, green, blue);
}
function generateHex(r, g, b) {
    r = r.toString(16);
    g = g.toString(16);
    b = b.toString(16);

    // to address problem mentioned by Alexis Wilke:
    while (r.length < 2) {
        r = "0" + r;
    }
    while (g.length < 2) {
        g = "0" + g;
    }
    while (b.length < 2) {
        b = "0" + b;
    }

    return "#" + r + g + b;
}
function mix(start, end, percent) {
    return start + ((percent) * (end - start));
}



// 获取有权限的菜单权限
export function getPermissionMenu(myMenus = []){
    let allMenuIds = getWorkFlowAllMenuIds(store.state.workFlowAllMenu);
    return getMenus(myMenus, allMenuIds);
    
}
// 过滤出没有权限的菜单
function getMenus(list, allMenuIds){
    if(!(list && list.length > 0)) return [];
    return list.filter(item => {
        if(item.list && item.list.length) {
            item.list = getMenus(item.list, allMenuIds);
        }
        // 如果不校验，则直接返回true，否则按照接口返回的数据判断
        return !item.isValidate || allMenuIds.includes(item.menu_id);
    });
}
// 获取接口返回的菜单权限
/**
 * @param {Array} list 菜单数据列表 
 */
export function getWorkFlowAllMenuIds(list = []){
    if(list && list.length) {
        let menuIds = [];
        list.forEach(item => {
            menuIds.push(...getWorkFlowAllMenuIds(item.childrens), item.menu_id);
        })
        return menuIds;
    }else {
        return [];
    }
    
}


// 数字浮点数精度的问题
export function formatFloat (f, digit) {
    var m = Math.pow(10, digit);
    return Math.round(f * m, 10) / m;
}





export const staticSource = {
	authorBg: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/authorBg.png',
	footerBg: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/footerBg.png',
	loginImg: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/loginImg.png',
	maskGroup: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/maskGroup.png',
	// tabShezhi: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/tabShezhi.png',
	// tabShezhiActive: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/tabShezhiActive.png',
	// tabShouye: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/tabShouye.png',
	// tabShouyeActive: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/tabShouyeActive.png',
	// tabTongji: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/tabTongji.png',
	// tabTongjiActive: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/tabTongjiActive.png',
	// tabXiaoxi: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/tabXiaoxi.png',
	// tabXiaoxiActive: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/tabXiaoxiActive.png',
	user: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/user.png',
	userBlue: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220618/userBlue.png',
	emptyImg: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20220624/emptyImg.png',
	homeBackImage: 'https://v5demo.sh-fengze.com/api/ApiDownLoad/api/Image/show/workflow?filepath=/20230524/homeBackImage.png'
}
